#!/usr/bin/python
# -*- coding: utf-8 -*- 

##获取oms接口数据，解析成项目信息，调用相应playbook进行发布

from ansible_api import ResultCallback, MyAnsible
import requests
import json
import argparse
import sys

API = "https://oms.ipaychat.net/api/publishs/"

def args():
    '''
    定义需要的参数
    project_name: oms中项目名称以及jenkins中项目名称
    extra_parameter: 其他参数
    '''
    extra_json = "{}"
    parser = argparse.ArgumentParser(description='deploy system base usage, example deploy_system_base.py -p jetty-deploy-system-base')
    parser.add_argument('--project', '-p', dest='project_name', default='none',  help='set jenkins project name')
    parser.add_argument('--extra', '-e', dest='extra_parameter', default=extra_json,  help='set jenkins extra parameters')
    args = parser.parse_args()
    return args

def parse_data(url, project_name):
    '''
    解析接口参数
    '''
    url = url + '?key[server_name]=' + project_name

    res = requests.get(url=url)
    target = res.json()
    return target


args = args()
hosts_inventory = parse_data(API, args.project_name)['data'][0]
hosts_inventory = dict(hosts_inventory, **eval(args.extra_parameter)) #结合页面传参
hosts_json = json.loads(json.dumps(hosts_inventory, sort_keys=True, indent=4))

ansible2 = MyAnsible(inventory='/etc/ansible/hosts', connection='smart', extra_vars=hosts_json)
#传入playbooks参数，需要的是一个列表数据类型，这里使用相对路径
#相对路径是相对于执行脚本的当前用户的家目录
ansible2.playbook(playbooks=["playbooks/" + hosts_json['stype'] + '.yml'])
result = json.loads(ansible2.get_result())
print(ansible2.get_result())

        
   



